package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.FeignService;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.vo.PageResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private FeignService feignService;
    @Override
    public PageResult queryList(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            Integer size = requestParams.getSize();
            Integer page = requestParams.getPage();
            String sortBy = requestParams.getSortBy();
            String location = requestParams.getLocation();
            getRequest(requestParams, request);
            request.source().from((page - 1) * size).size(size);
            getSort(request, sortBy, location);
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return getPageResult(search);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            getRequest(requestParams, request);
            getAggBuilder(request);
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> map = new HashMap<>();
            List<String> brandAgg = getAgg(response, "brandAgg");
            List<String> cityAgg = getAgg(response, "cityAgg");
            List<String> starNameAgg = getAgg(response, "starNameAgg");
            map.put("brand",brandAgg);
            map.put("city",cityAgg);
            map.put("starName",starNameAgg);
            return map;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public List<String> getSuggestion(String key) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            request.source().suggest(new SuggestBuilder().addSuggestion("mySuggestion",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key).skipDuplicates(true).size(10)));
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion mySuggestion = response.getSuggest().getSuggestion("mySuggestion");
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void delete(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("hotel").id(id.toString());
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void insert(Long id) {
        try {
            IndexRequest request = new IndexRequest("hotel").id(id.toString());
            Hotel hotel = feignService.findById(id);
            if (hotel == null)return;
            HotelDoc hotelDoc = new HotelDoc(hotel);
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<String> getAgg(SearchResponse response,String aggName) {
        Terms terms = response.getAggregations().get(aggName);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    private void getAggBuilder(SearchRequest request) {
        request.source().size(0).aggregation(
                AggregationBuilders.terms("brandAgg").field("brand").size(10)
        );
        request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(10));
        request.source().aggregation(AggregationBuilders.terms("starNameAgg").field("starName").size(10));
    }

    private void getSort(SearchRequest request, String sortBy, String location) {
        if (StringUtils.isNotBlank(location)){
            request.source().sort(SortBuilders.
                    geoDistanceSort("location",new GeoPoint(location)
            ).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
        }
        if (sortBy.equals("score")){
            request.source().sort("score",SortOrder.DESC);
        }else if (sortBy.equals("price")){
            request.source().sort("price",SortOrder.ASC);
        }
//        request.source().sort("pay",SortOrder.DESC);
    }

    private void getRequest(RequestParams requestParams, SearchRequest request) {
        String key = requestParams.getKey();
        String brand = requestParams.getBrand();
        String city = requestParams.getCity();
        String starName = requestParams.getStarName();
        Integer maxPrice = requestParams.getMaxPrice();
        Integer minPrice = requestParams.getMinPrice();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isBlank(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }
        if (StringUtils.isNotBlank(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
        if (StringUtils.isNotBlank(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",brand));
        }
        if (maxPrice != null && minPrice != null && minPrice >= 0 && maxPrice >= minPrice) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice).gte(minPrice));
        }
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10f))  //按照广告费添加权重？？？？还是按照广告费排序
                }
        ).boostMode(CombineFunction.SUM);
        request.source().query(functionScoreQuery);
    }

    private PageResult getPageResult(SearchResponse search) {
        SearchHit[] hits = search.getHits().getHits();
        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields!=null&&!highlightFields.isEmpty()){
                HighlightField highlightField = highlightFields.get("name");
                String join = StringUtils.join(highlightField.getFragments());
                hotelDoc.setName(join);
            }
            Object[] sortValues = hit.getSortValues();
            if (sortValues != null && sortValues.length >0){
                hotelDoc.setDistance(sortValues[0]);
            }
            hotels.add(hotelDoc);
        }
        long total = search.getHits().getTotalHits().value;
        return new PageResult(total, hotels);
    }

}
